package com.jshoperxms.components.wechat;

import com.jshoperxms.components.redis.RedisUtils;
import com.jshoperxms.components.wechat.bean.TokenBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by sdywcd on 2019/1/30.
 * Des:
 */
@Component
public class WxTokenUtils {

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private RedisUtils redisBaseOperation;

    public String getToken(){
        Object accessToken=redisBaseOperation.getObjectByKey("accesstoken");
        System.out.println("acctoken是"+accessToken);
        //accessToken=null;
        if(accessToken!=null){
            accessToken=redisBaseOperation.getObjectByKey("accesstoken");
        }else{
            String url="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential" +
                    "&appid={appid}" +
                    "&secret={secret}";
            Map<String,Object> params=new HashMap<>();
            params.put("appid", WxConfig.appid);
            params.put("secret",WxConfig.serect);
            ResponseEntity<TokenBean> tkb=restTemplate.getForEntity(url,TokenBean.class,params);
            TokenBean tokenBean=tkb.getBody();
            if(tokenBean!=null){
                System.out.println("acctoken新的"+accessToken);
                accessToken=tokenBean.getAccess_token();
                redisBaseOperation.setObjectEx("accesstoken",7000, tokenBean.getAccess_token());
            }
       }
        return accessToken.toString();
    }

}
